package com.github.m6d21.sso.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *<p>
 *类似guava joiner splitter，通过正则过滤字符串中的字符
 *</p>
 *
 * @author liuyang
 * @date 2018/12/7 Fri 17:08:00
 * @since 1.0.0
 */
public class StringFilter {

    private String source;

    private List<CharSequence> dirtyList = new ArrayList<>();

    /**
     * 防止StringFilter被手动new
     * @param source 源字符串
     */
    private StringFilter(String source) {
        this.source = source;
    }

    public static StringFilter on(String source) {
        return new StringFilter(source);
    }

    /**
     * 要过滤的字符
     * @param sequence 过滤的字符串
     * @return this
     */
    public StringFilter filter(CharSequence sequence) {
        dirtyList.add(wrap(sequence));
        return this;
    }

    public String done() {
        if (dirtyList.size() <= 0) {
            return source;
        }
        dirtyList = dirtyList.stream().distinct().collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for (CharSequence c : dirtyList) {
            sb.append(c).append("|");
        }
        String regexp = sb.substring(0, sb.length() - 1);
        return source.replaceAll(regexp, "");
    }

    private StringBuilder wrap(CharSequence sequence) {
        return new StringBuilder("(").append(sequence).append(")");
    }
}
